Parse.Cloud.beforeSave('RcCashRecord', async (req, res) => {
  try {
    const cashRecord = req.object
    const type = cashRecord.get('type')
    if (type === 'withdraw') {
      const id = cashRecord.id
      const member = cashRecord.get('member')
      const money = cashRecord.get('money')
      const wallet = await new Parse.Query('RcWallet').equalTo('member', member).first()
      if (!wallet) {
        return res.error('钱包没钱，不能提现')
      }
      const total = wallet.get('total')
      if (id) {
        const status = cashRecord.get('status')
        const prevCashRecord = await new Parse.Query('RcCashRecord').equalTo('objectId', id).first()
        const prevStatus = prevCashRecord.get('status')
        const prevMoney = prevCashRecord.get('money')

        if (status === prevStatus) {
          return res.success()
        }

        const cashCount = await new Parse.Query('RcCashCount').first()
        if (status === 1) {
          await wallet.increment('lock', -prevMoney).increment('successCount', 1).increment('success', prevMoney).save()
          cashRecord.set('finishedAt', new Date())
          cashCount.increment('lock', -prevMoney).increment('success', prevMoney).increment('successCount', 1)
        }

        if (status === -1) {
          await wallet.increment('total', prevMoney).increment('lock', -prevMoney).save()
          cashRecord.set('finishedAt', new Date())
          cashCount.increment('lock', -prevMoney).increment('remaining', prevMoney)
        }

        await cashCount.save()
        res.success()
      } else {
        const config = await Parse.Config.get()
        const limitMoney = config.get('RcLimitMoney')
        const shareRate = config.get('RcShareRate')
        if (total < limitMoney) {
          return res.error(`提现金额不足${limitMoney}元，不能提现`)
        }
        if (money > total) {
          return res.error(`你的余额只有${total}元，不能提现`)
        }
        await wallet.increment('total', -money).increment('lock', money).save()

        const shareMoney = parseFloat((money * shareRate / 100).toFixed(2))

        cashRecord.set('shareMoney', shareMoney).set('actualMoney', parseFloat((money - shareMoney).toFixed(2)))

        const cashCount = await new Parse.Query('RcCashCount').first()
        cashCount.increment('remaining', -money).increment('lock', money)
        await cashCount.save()
        res.success()
      }
    } else {
      res.success()
    }
  } catch (err) {
    console.log(err)
  }
})

